package com.addcn.caruimodule.image;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.ClipDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatImageView;

import com.addcn.caruimodule.R;


/**
 * Created by 10528 on 2017/9/7.
 */

public class UploadImageView extends AppCompatImageView {
    //遮罩drawable
    private Drawable mShaderDrawable;
    //read error drawable
    private Drawable mReadErrorDrawable;
    //upload failure drawable
    private Drawable mUploadFailDrawable;
    private Rect mRect=new Rect();
    private boolean mDrawShader;

    public UploadImageView(Context context) {
        this(context,null);
    }

    public UploadImageView(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray a=context.obtainStyledAttributes(attrs, R.styleable.UploadImageView);
        setShaderDrawable((ClipDrawable) a.getDrawable(R.styleable.UploadImageView_shader_drawable));
        setReadErrorImage(a.getDrawable(R.styleable.UploadImageView_read_error_drawable));
        setUploadFailDrawable(a.getDrawable(R.styleable.UploadImageView_upload_fail_drawable));
        a.recycle();
    }

    public void setShaderDrawable(ClipDrawable drawable){
        mDrawShader=true;
        mShaderDrawable=drawable;
    }

    public void setProgress(int progress){
        if(mShaderDrawable!=null) {
            mShaderDrawable.setLevel(Math.round(10000 * (1-progress / 100.0f)));
            invalidate();
        }
    }

    public void setReadErrorImage(Drawable dr){
        mReadErrorDrawable=dr;
    }

    public void setUploadFailDrawable(Drawable dr){
        mUploadFailDrawable=dr;
    }

    public void readError(){
        mDrawShader=false;
        if(mReadErrorDrawable!=null) {
            setImageDrawable(mReadErrorDrawable);
        }
    }

    public void uploadFail(){
        mDrawShader=false;
        if(mUploadFailDrawable!=null){
            setImageDrawable(mUploadFailDrawable);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if(mShaderDrawable!=null&&mDrawShader) {
            mShaderDrawable.setBounds(mRect);
            mShaderDrawable.draw(canvas);
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mRect.set(0,0,w,h);
    }
}
